//
// Created by user on 2022/3/1.
//
#include <vector>
#include <algorithm>
using namespace std;
int trap(vector<int>& height) {
    int n = height.size();
    if (n <= 2) return 0;

    vector<int> leftMax(n);
    leftMax[0] = height[0];
    for (int i = 1; i < n; i++) {
        leftMax[i] = max(leftMax[i - 1], height[i]);
    }

    vector<int> rightMax(n);
    rightMax[n - 1] = height[n - 1];
    for (int i = n - 2; i >= 0; i--) {
        rightMax[i] = max(rightMax[i + 1], height[i]);
    }

    int ans = 0;
    for (int i = 1; i < n - 1; i++) {
        int maxHeight = min(leftMax[i], rightMax[i]);
        if (maxHeight > height[i])
            ans += maxHeight - height[i];
    }

    return ans;

}
